package com.htthorizon.model.controller;

import com.alibaba.cloudapi.sdk.model.ApiResponse;
import com.alibaba.cloudapi.sdk.model.HttpClientBuilderParams;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONException;
import com.alibaba.fastjson2.JSONObject;
import com.htthorizon.common.core.utils.StringUtils;
import com.htthorizon.common.log.annotation.Log;
import com.htthorizon.common.log.enums.BusinessType;
import com.htthorizon.model.config.APIInfo;
import com.htthorizon.model.config.TableNameConfig;
import com.htthorizon.model.domain.ModelMeta;
import com.htthorizon.model.response.MetaDataDto;
import com.htthorizon.model.response.MetaInfoDto;
import com.htthorizon.model.response.RemoteDataInfoDto;
import com.htthorizon.model.service.IModelMetaService;
import com.htthorizon.util.DynamicCreateTableUtil;
import com.htthorizon.util.SDKGetAPIUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @author Brilliant ,
 */
@RestController
@RequestMapping("api")
public class TestController {

    @Autowired
    private TableNameConfig tableNameConfig;


    @Autowired
    private SDKGetAPIUtil sdkGetAPIUtil;


    @Value("${meta.AppKey}")
    private String META_APPKEY;

    @Value("${meta.AppCode}")
    private String META_APPCODE;

    @Value("${meta.AppSecre}")
    private String META_APPSECRE;

    @Value("${meta.path}")
    private String path;

    @Autowired
    private IModelMetaService modelMetaService;

    @Autowired
    private DynamicCreateTableUtil dynamicCreateTableUtil;
    @GetMapping("/test")
    public String test(){
        for (APIInfo apiInfo : tableNameConfig.getApiInfos()){
            String tableName = apiInfo.getTableName();
            String tableNameZn = apiInfo.getTableNameZn();
            String appKey = META_APPKEY;
            String path = this.path;
            String appSecret = META_APPSECRE;
            HttpClientBuilderParams httpParam = new HttpClientBuilderParams();
            httpParam.setAppKey(appKey);
            httpParam.setAppSecret(appSecret);

            sdkGetAPIUtil.init(httpParam);



            ApiResponse apiResponse = sdkGetAPIUtil.getMetaDataByTb(path, tableName);

            String result=null;

            if (apiResponse.getCode()==200){

                result= new String(apiResponse.getBody(), StandardCharsets.UTF_8) ;

            }

            System.out.println("result : " + result);

            if(StringUtils.isNotEmpty(result)){
                Optional<MetaInfoDto> metaInfoDtoOpt = null;
                try {
                    JSONObject jsonObject =  JSON.parseObject(result);
                    metaInfoDtoOpt = Optional.ofNullable(JSONObject.parseObject(jsonObject.getString("data"), MetaInfoDto.class));
                }catch (JSONException e){
                    System.out.println("获取远程模型元数据json格式异常");
                }
                if(metaInfoDtoOpt.isPresent()) {
                    MetaInfoDto metaInfoDto = metaInfoDtoOpt.get();
                    List<MetaDataDto> rows = metaInfoDto.getRows();
                    if(CollectionUtils.isEmpty(rows)){
                        System.out.println("元数据列表为空！");
                    }
                    ModelMeta modelMeta = null;
                    List<ModelMeta> modelMetaList = new ArrayList<>(rows.size());
                    for (int i=0; i<rows.size(); i++){
                        MetaDataDto dto = rows.get(i);
                        modelMeta = new ModelMeta();
                        modelMeta.setMetaFieldSort(i+1);
                        modelMeta.setMetaFieldName(dto.getName());
                        modelMeta.setMetaFieldRemark(dto.getCol_comment());
                        modelMeta.setMetaFieldType(dto.getType());
                        modelMeta.setModelName(dto.getModel_tb());
                        modelMeta.setTableName(tableName);
                        modelMetaList.add(modelMeta);
                    }
                    System.err.println(tableName);
                    System.out.println("modelMetaList-------->"+modelMetaList);
                    System.err.println("删除表元数据信息");
                    modelMetaService.deleteModelMetaByTableName(tableName);
                    System.err.println("删除表元数据信息");
                    for (ModelMeta model: modelMetaList){
                        modelMetaService.insertModelMeta(model);
                    }
                   int res= modelMetaService.createTableByTableName(tableName,tableNameZn);
                }
            }else{
                System.out.println("获取远程元数据异常");
            }

        }

        return "成功";
    }


    @GetMapping("/test1")
    @Log(title = "同步数据", businessType = BusinessType.QUERY)
    public String test1(){
        for (APIInfo apiInfo : tableNameConfig.getApiInfos()){

            String tableName = apiInfo.getTableName();
            dynamicCreateTableUtil.truncate(tableName);
            String appKey = apiInfo.getAppKey();

            String path = apiInfo.getPath();

            String appSecret = apiInfo.getAppSecret();

            HttpClientBuilderParams httpParam = new HttpClientBuilderParams();

            httpParam.setAppKey(appKey);

            httpParam.setAppSecret(appSecret);

            sdkGetAPIUtil.init(httpParam);


            List<ModelMeta> list = modelMetaService.selectModelMetaByTableName(tableName);

            ApiResponse apiResponse = sdkGetAPIUtil.searchByParams2(path);

            String result=null;

            if (apiResponse.getCode()==200){

                result= new String(apiResponse.getBody(), StandardCharsets.UTF_8) ;

            }

            System.out.println("result : " + result);

            if(StringUtils.isNotEmpty(result)) {

                Optional<RemoteDataInfoDto> dataOpt = null;

                try {

                    JSONObject jsonObject = JSON.parseObject(result);

                    dataOpt = Optional.ofNullable(JSONObject.parseObject(jsonObject.getString("data"), RemoteDataInfoDto.class));

                }catch (JSONException e){

                    return null;

                }
                if (dataOpt.isPresent()) {

                    RemoteDataInfoDto dataInfoDto = dataOpt.get();

                    this.page(dataInfoDto, 2000, sdkGetAPIUtil, path, tableName,httpParam);
// todo 分页 先获取数据条数,在分页下载
//                    List<?> dataList = dataInfoDto.getRows();
//
//                    //设置表头,获取api返回数据中的一条数据，设置中文字段表头
//                    if(StringUtils.isNotEmpty(dataList)) {
//                       String sql= dynamicCreateTableUtil.initData(tableName,dataList);
//                    }
                }else {
                    return null;
                }
            }else{

            }

        }

        return "成功";
    }

    private void page(RemoteDataInfoDto dataInfoDto,Integer span,SDKGetAPIUtil sdkGetAPIUtil,String path,String tableName, HttpClientBuilderParams httpParam){
        Integer total = dataInfoDto.getTotalNum();
        if (span >= total){
            String result=null;
            sdkGetAPIUtil.init(httpParam);
            ApiResponse apiResponse = sdkGetAPIUtil.searchByParams3(path, "1", String.valueOf(span));
            if (apiResponse.getCode()==200){
                result= new String(apiResponse.getBody(), StandardCharsets.UTF_8) ;
            }

            if(StringUtils.isNotEmpty(result)) {

                Optional<RemoteDataInfoDto> dataOpt = null;

                try {
                    JSONObject jsonObject = JSON.parseObject(result);
                    dataOpt = Optional.ofNullable(JSONObject.parseObject(jsonObject.getString("data"), RemoteDataInfoDto.class));
                }catch (JSONException e){
                    e.printStackTrace();
                }
                if (dataOpt.isPresent()) {
                    RemoteDataInfoDto dataInfoDto1 = dataOpt.get();
                    List<?> dataList = dataInfoDto1.getRows();
                    //设置表头,获取api返回数据中的一条数据，设置中文字段表头
                    if(StringUtils.isNotEmpty(dataList)) {
                        String sql= dynamicCreateTableUtil.initData(tableName,dataList);
                    }
                }
            }
        }
        if (span < total){
            long size = total / span;
            if (total % span != 0) {
                for (int i = 1; i <= size + 1; i++) {
                    String result=null;
                    sdkGetAPIUtil.init(httpParam);
                    ApiResponse apiResponse = sdkGetAPIUtil.searchByParams3(path, String.valueOf(i), String.valueOf(span));
                    if (apiResponse.getCode()==200){
                        result= new String(apiResponse.getBody(), StandardCharsets.UTF_8) ;
                    }

                    if(StringUtils.isNotEmpty(result)) {

                        Optional<RemoteDataInfoDto> dataOpt = null;

                        try {
                            JSONObject jsonObject = JSON.parseObject(result);
                            dataOpt = Optional.ofNullable(JSONObject.parseObject(jsonObject.getString("data"), RemoteDataInfoDto.class));
                        }catch (JSONException e){
                            e.printStackTrace();
                        }
                        if (dataOpt.isPresent()) {
                            RemoteDataInfoDto dataInfoDto1 = dataOpt.get();
                            List<?> dataList = dataInfoDto1.getRows();
                            //设置表头,获取api返回数据中的一条数据，设置中文字段表头
                            if(StringUtils.isNotEmpty(dataList)) {
                                String sql= dynamicCreateTableUtil.initData(tableName,dataList);
                            }
                        }
                    }

                }
            } else {
                for (int i = 1; i <= size; i++) {
                    String result=null;
                    sdkGetAPIUtil.init(httpParam);
                    ApiResponse apiResponse = sdkGetAPIUtil.searchByParams3(path, String.valueOf(i), String.valueOf(span));
                    if (apiResponse.getCode()==200){
                        result= new String(apiResponse.getBody(), StandardCharsets.UTF_8) ;
                    }

                    if(StringUtils.isNotEmpty(result)) {

                        Optional<RemoteDataInfoDto> dataOpt = null;

                        try {
                            JSONObject jsonObject = JSON.parseObject(result);
                            dataOpt = Optional.ofNullable(JSONObject.parseObject(jsonObject.getString("data"), RemoteDataInfoDto.class));
                        }catch (JSONException e){
                           e.printStackTrace();
                        }
                        if (dataOpt.isPresent()) {
                            RemoteDataInfoDto dataInfoDto2 = dataOpt.get();
                            List<?> dataList = dataInfoDto2.getRows();
                            //设置表头,获取api返回数据中的一条数据，设置中文字段表头
                            if(StringUtils.isNotEmpty(dataList)) {
                                String sql= dynamicCreateTableUtil.initData(tableName,dataList);
                            }
                        }
                    }
                }
                }
            }
    }
}
